import datetime
import pytz
from django.core import signing
from rest_framework.decorators import api_view
from questionnaire.models import Questionnaire, Question, Options, GradeQuestionAttribute
from rest_framework.response import Response
from rest_framework import status
from django.http import HttpResponse
import qrcode
from MyQR import myqr
import six
from six import BytesIO

from djangoProject.settings import *


# 前端首先请求发布问卷生成url 如果问卷不存在或者问卷已发布 则在前端提示相应信息
# 在未出错的情况下向后端请求生成二维码 生成二维码中不对错误questionnaire_id进行拦截
@api_view(['POST', ])
def publishQuestionnaireFirstly(request):
    questionnaire_id = request.data.get('questionnaire_id')
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在该问卷'}, status=status.HTTP_404_NOT_FOUND)
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    if questionnaire.status == 1:
        return Response({'code': -2, 'msg': '问卷已发布'}, status=status.HTTP_200_OK)
    questionnaire.status = 0
    now = datetime.datetime.now().replace(tzinfo=pytz.timezone('UTC'))
    questionnaire.publish_time = now
    questionnaire.save()
    value = signing.dumps({'questionnaire_id': questionnaire_id})
    # 此处生成一个链接 （待修改

    url = DEFAULT_URL + 'questionnaire/' + value

    return Response({'url': url}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def createQrCode(request):
    questionnaire_id = request.data.get('questionnaire_id')
    # value = str(questionnaire_id)
    value = signing.dumps({'questionnaire_id': questionnaire_id})
    url = "http://8.140.186.185:8008/deliver/" + value
    # url = DEFAULT_URL + 'deliver/' + value

    name = 'media//qrcode//' + value + '.jpg'
    myqr.run(words=url, save_name=name, )
    # url_ = 'http://8.140.186.185:8008/media/qrcode/' + str(questionnaire_id) + '.jpg'
    url_ = DEFAULT_URL + 'media/qrcode/' + value + '.jpg'

    response = {
        'code': 0,
        'msg': '',
        'url': url_
    }
    return Response(response, status=status.HTTP_200_OK)
